package com.eusoft.book_manage.util;

import com.eusoft.book_manage.entity.BookType;

import java.util.List;
import java.util.stream.Collectors;

/**
 * getlevel、checkFatherClassification、checkSubclass
 * @author eusoft
 * @date 2021/10/20 9:25
 */
public class CommonUtil {
    /**
     * 获取当前分类的层级level
     * @param level 顶级分类的level
     * @param pId   分类的父级aid
     * @param types 分类list
     * @return 该分类的level
     */
    public static Integer getlevel(Integer level ,Integer pId,List<BookType> types){

        if(pId == null)
            return 0;
        for (BookType type :types){
            Integer parentAid = type.getAid(); //父级类型的aid
            if(parentAid.equals(pId)){
                Integer parentPId =type.getFatherAid(); //父级类型的fatherAid
                if(parentPId !=null)
                {
                    level++;
                    return getlevel(level,parentPId,types);
                }
            }
        }
        return level;
    }

    /**
     * 检查分类的父级类型aid 是否是该类型的子类
     * @param aid 类型的aid
     * @param pId 父级类型aid
     * @param types 类型数组
     * @return boolean
     */
    public static Boolean checkFatherClassification(Integer aid, Integer pId, List<BookType> types){
        //获取子类
        List<BookType> tyepList = types.stream().filter(x->x.getFatherAid().equals(aid)).collect(Collectors.toList());
        //获取非子类
        List<BookType> successor = types.stream().filter(x->!x.getFatherAid().equals(aid)).collect(Collectors.toList());
        //检查子类的aid
        for(BookType type :tyepList){
            if(type.getAid().equals(pId)){
                throw new RuntimeException("find");
            }
            else{
                //获取子类的子类与非子类进行检查
                checkFatherClassification(type.getAid(),pId,successor);
            }
        }
        return false;
    }

    /**
     * 对类型数组进行二次处理，将有子类的类型的isDelete属性设为true(表示被子类占用)
     * @param types 类型数组
     * @return 类型数组
     */
    public static List<BookType> checkSubclass(List<BookType> types){
        //x.aid == y.fatherAid ->x有子类
        types.forEach(x->{
            types.forEach(y->{
                if(x.getAid().equals(y.getFatherAid())){
                    x.setIsDelete(true);
                }
            });
        });
        return types;
    }

}
